﻿using System;
using System.Collections.Generic;
using System.Reflection;
using Validate.Net.Tools;

namespace Validate.Net
{
    public static class AttributeHelper
    {
        /// <summary>
        /// 获取属性描述信息[Describe]
        /// </summary>
        /// <param name="prop"></param>
        /// <returns></returns>
        public static string GetColumnDescribe(this PropertyInfo prop)
        {
            return CacheColumnDescribe.GetColumnDescribe(prop);
        }

        /// <summary>
        /// 校验实体类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="errorList">错误信息集合</param>
        /// <returns></returns>
        public static bool Validate<T>(this T t, out List<string> errorList) where T : new()
        {
            errorList = new List<string>();
            var properties = CachePropertyAttribute<T>.PropertiesCache.Keys;
            foreach (PropertyInfo prop in properties)
            {
                var propValue = prop.GetValue(t, null);
                var attributeArray = CachePropertyAttribute<T>.PropertiesCache[prop];
                foreach (AbstractValidateAttribute attribute in attributeArray)
                {
                    if (!attribute.Validate(propValue, out string msg))
                    {
                        errorList.Add($"属性：{prop.GetColumnDescribe()} - 值：{(propValue == null ? "null" : propValue)}  错误信息： {msg}");
                    }
                }
            }
            return errorList.Count == 0;
        }

    }
}
